package tech.treec.smartlight.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.fastjson.JSONObject;
import com.young.mylib.db.dao.DeviceDao;
import com.young.mylib.db.entity.DeviceDataEntity;
import com.young.mylib.db.entity.LinkageLog;
import com.young.mylib.utils.JsonUtils;
import com.young.mylib.utils.TimeUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import tech.treec.smartlight.R;
import tech.treec.smartlight.adapter.MyListAdapter;

public class LogActivity extends BaseActivity {
    private static String TAG = "LogActivity";
    @BindView(R.id.lv_data)
    ListView lvData;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.btnNext)
    Button btnNext;
    int _time = -1;
    List<String> datas = new ArrayList<>();
    MyListAdapter adapter;

    @Override
    protected int setLayoutID() {
        return R.layout.activity_device_data;
    }

    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected void initView() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
        adapter = new MyListAdapter(getApplicationContext(), R.layout.data_item, datas);
        lvData.setAdapter(adapter);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onClick(View v) {
                _time=_time-10;
                String time = TimeUtils.long2str(_time);
                tvTime.setText(time);
                loadData(_time);
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {

            onBackPressed(); // 调用onBackPressed()方法来处理返回操作
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void loadData() {
        String time = TimeUtils.long2str(_time);
        tvTime.setText(time);
        loadData(_time);

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void loadData(int _time) {
        datas.clear();
        showProgressDialog("数据加载中", true);
        // 步骤1：通过匿名类 直接 创建线程辅助对象，即 实例化 线程辅助类
        Runnable mt = new Runnable() {
            // 步骤2：复写run（），定义线程行为
            @Override
            public void run() {
                long beforeTs = TimeUtils.getCurrTsBeforeHour(_time);

                Log.i(TAG, "load device data " + beforeTs);
                List<LinkageLog> list = DeviceDao.findLinkageLogByRange(beforeTs);
                if (list == null) return;
                //   Log.i(TAG, "查找LOG数据:"+list.size());
                list.sort(new Comparator<LinkageLog>() {
                    @Override
                    public int compare(LinkageLog o1, LinkageLog o2) {
                        return Long.compare(o2.ts, o1.ts);
                    }
                });

                for (LinkageLog entity : list) {
                    JSONObject json = JsonUtils.toJSON(entity);

                    datas.add(entity.name + " 时间：" + entity.time + " 信息：" + entity.msg);
                }

                //   List<DeviceDataEntity> list = DeviceDao.findAll();
                Message msg = new Message();
                msg.what = 0;
                mHandler.sendMessage(msg);
            }
        };
        Thread mt1 = new Thread(mt);
        mt1.start();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dismissProgressDialog("");
            adapter.notifyDataSetChanged();
        }
    };
}

